package com.yld.oa.department.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.yld.oa.department.dao.DepartmentDao;
import com.yld.oa.department.entity.DepartmentEntity;
import com.yld.util.DBUtil;

public class DepartmentDaoImpl implements DepartmentDao {

	@Override
	public DepartmentEntity findById(Integer id) {
		
		DepartmentEntity  department=new DepartmentEntity();
		
		//1 连接oracle数据库
		Connection connection = DBUtil.getConnection();
		
		System.out.println("DepartmentDao connection"+connection);
		
		
		//2 准备sql 占位符  规定 凡是查找的代码 不允许用select *   要用as  在mybatis中是根据as后面的值自动赋值给对应的属性
		String sql ="SELECT ID AS id, DEPARTMENT_NAME AS departmentName  FROM OA_DEPARTMENT_T WHERE ID=?";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			//3把字符串封装成可执行的sql命令    准备好的执行语句
			ps= connection.prepareStatement(sql);
			
			
			//4对参数给定具体的值
			ps.setInt(1, id);
			
			//5执行命令
			rs = ps.executeQuery();
			
			
			//? 判断结果集中有没有数据  有多少数据?

			if(rs.next()){
				System.out.println("有数据....");
				
				Integer ic  = rs.getInt("id");
				String departmentName = rs.getString("departmentName");
				
				department.setId(ic);
				department.setDepartmentName(departmentName);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			
			//aop
			DBUtil.closeResultSet(rs);
			DBUtil.closePreparedStatement(ps);
			DBUtil.closeConnection(connection);
			
		}
		
		return department;
	}

	@Override
	public void addDepartment(DepartmentEntity department,Connection connection) {
		
		System.out.println("DepartmentDao connection"+connection);
		//2 准备sql 占位符
		String sql ="INSERT INTO OA_DEPARTMENT_T(ID,DEPARTMENT_NAME) VALUES(?,?)";
		
		PreparedStatement ps = null;
		try {
			//3把字符串封装成可执行的sql命令    准备好的执行语句
			ps = connection.prepareStatement(sql);
			
			//4对参数给定具体的值
			ps.setInt(1, department.getId());
			ps.setString(2, department.getDepartmentName());
			
			//5执行命令
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtil.closePreparedStatement(ps);
			//DBUtil.closeConnection(connection);
		}
		
	}

}
